﻿using CXW.Core.Sharp.Services;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Docking;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace CXW.Core.Sharp.Gui
{
    public partial class WorkBenchWindow : BaseForm
    {
        /// <summary>主窗体构造函数</summary>
        public WorkBenchWindow()
        {
            InitializeComponent();

            OnLanguageChanged();
        }
        /// <summary>变更UI显示语言时执行此方法</summary>
        public override void OnLanguageChanged()
        {
            base.OnLanguageChanged();

            MenuService.UpdateText(MenuBar);
            MenuService.UpdateText(ToolBar);
            dockManager1.UpdateText();
            foreach (XtraTabPageExt xTabPageExt in xtraTabControl1.TabPages)
            {
                xTabPageExt.ChangePageTitle();
            }

            if (_activateViewContent != null) { _activateViewContent.ActivateViewContentChanged2(); }
        }


        /// <summary>缓存当前皮肤名称对应菜单的ID</summary>
        string _skinName = "";
        /// <summary>缓存底部状态栏的显示状态(除第一次调用外,和实际状态相反)</summary>
        bool _statusBarShow { get; set; }
        /// <summary>缓存所有DockPanel的显示状态(除第一次调用外,和实际状态相反)</summary>
        Dictionary<string, bool> _dockPanel = new Dictionary<string, bool>();


        const string menuPath = "/CML/MainMenu";
        const string toolPath = "/CML/ToolMenu";
        const string treePath = "/CML/TreeMenu";

        /// <summary>初始化</summary>
        public void Initialize()
        {
            BarSubItem _barSubItem = null;
            new MenuService(barManager1).CreateMenuItems<ToolbarItemDescriptor>(ToolBar, this, toolPath, ref _barSubItem);//先调用此方法,ref参数始终为空
            new MenuService(barManager1).CreateMenuItems<MenuItemDescriptor>(MenuBar, this, menuPath, ref _barSubItem);

            new DockPanelService(dockManager1).CreateDockPanel(treePath, this);

            if (_barSubItem != null && dockManager1.DockPanelAllCollection.Count > 0)
            {
                CreateMenuShowDockPanel(_barSubItem, dockManager1.DockPanelTopCollection);
                CreateMenuShowDockPanel(_barSubItem, dockManager1.DockPanelLeftCollection);
                CreateMenuShowDockPanel(_barSubItem, dockManager1.DockPanelBottomCollection);
                CreateMenuShowDockPanel(_barSubItem, dockManager1.DockPanelRightCollection);
            }
        }

        void CreateMenuShowDockPanel(BarSubItem _barSubItem, IList<DockPanel> ilist)
        {
            foreach (DockPanel item in ilist)
            {
                BarButtonItemExt t = new BarButtonItemExt(item.Tag as Codon)
                {
                    ButtonStyle = BarButtonStyle.Check,
                    Down = true,
                    GroupIndex = 0
                };

                t.ItemClick += (sender, e) =>
                {
                    var dockVisible = _dockPanel.FirstOrDefault(r => r.Key == e.Item.Name);
                    if (string.IsNullOrWhiteSpace(dockVisible.Key)) { _dockPanel.Add(e.Item.Name, ((BarButtonItemExt)e.Item).Down); }

                    item.Visibility = (_dockPanel[e.Item.Name] ? DockVisibility.Visible : DockVisibility.Hidden);

                    ((BarButtonItemExt)e.Item).Down = _dockPanel[e.Item.Name];
                    _dockPanel[e.Item.Name] = !_dockPanel[e.Item.Name];
                };
                barManager1.Items.Add(t);
                _barSubItem.LinksPersistInfo.Add(new LinkPersistInfo(t));
            }
        }
        /// <summary>设置皮肤样式</summary>
        /// <param name="skinName"></param>
        internal override void SetLookAndFeel(string skinName)
        {
            _skinName = skinName;
            base.SetLookAndFeel(skinName);
        }
        /// <summary>设置底部状态栏显示状态</summary>
        internal void SetStatusBar()
        {
            StatusBar.Visible = _statusBarShow;
            _statusBarShow = !StatusBar.Visible;
        }

        /// <summary>根据配置设置默认状态</summary>
        /// <param name="properties"></param>
        internal void SetMemento(Properties properties)
        {
            _skinName = properties.Get("SkinName", "DevExpressStyle");

            _statusBarShow = properties.Get("StatusBarShow", true);

            BarButtonItemExt btnItem = null;
            foreach (BarItem barsubitem in barManager1.Items)
            {
                btnItem = barsubitem as BarButtonItemExt;
                if (btnItem != null)
                {
                    if (btnItem.Name == _skinName) { btnItem.PerformClick(); }
                    else if (btnItem.Name == "StatusBarShow")
                    {
                        btnItem.PerformClick();
                        btnItem.Down = !_statusBarShow;
                    }
                }
            }
        }
        /// <summary>根据配置设置默认状态</summary>
        /// <param name="properties"></param>
        internal void SetDockPanelVisabled(Properties properties)
        {
            string[] keys = properties.Elements;
            int i = 0;
            BarButtonItemExt btnItem = null;

            foreach (BarItem barsubitem in barManager1.Items)
            {
                btnItem = barsubitem as BarButtonItemExt;
                if (btnItem != null)
                {
                    foreach (string key in keys)
                    {
                        if (btnItem.Name == key)
                        {
                            if (_dockPanel.ContainsKey(key))
                            { _dockPanel[key] = properties.Get(key, true); }
                            else { _dockPanel.Add(key, properties.Get(key, true)); }

                            i++; btnItem.PerformClick(); break;
                        }
                    }
                }
                if (i == keys.Length) { break; }
            }
        }

        internal Properties CretatMemento()
        {
            Properties prop = new Properties();
            prop.Set("SkinName", _skinName);
            prop.Set("StatusBarShow", !_statusBarShow);
            return prop;
        }
        internal Properties CretatDockPanel()
        {
            Properties prop = new Properties();
            foreach (var dpe in _dockPanel)
            {
                prop.Set(dpe.Key, !dpe.Value);
            }
            return prop; ;
        }


        List<IViewContent> _viewContentCollection = new List<IViewContent>();
        /// <summary>返回已打开 <see cref="IViewContent"/> 的只读集合</summary>
        public ICollection<IViewContent> ViewContentCollection
        {
            get { return _viewContentCollection.AsReadOnly(); }
        }
        /// <summary>呈现UI对象,如果已存在,则激活</summary>
        /// <param name="content"></param>
        internal void ShowView(IViewContent content)
        {
            WorkbenchSingleton.AssertMainThread();
            if (content == null)
                throw new ArgumentNullException("content");
            if (_viewContentCollection.Contains(content))
            {
                if (!((content.Control as Control).Parent as XtraTabPageExt).PageVisible)
                {
                    ((content.Control as Control).Parent as XtraTabPageExt).PageVisible = true;
                    xtraTabControl1.TabPages.Move(xtraTabControl1.TabPages.Count, (content.Control as Control).Parent as XtraTabPageExt);
                }
                xtraTabControl1.SelectedTabPage = (content.Control as Control).Parent as XtraTabPageExt;
            }
            else
            {
                _viewContentCollection.Add(content);

                XtraTabPageExt xTabPageExt = new XtraTabPageExt(content);
                xTabPageExt.Control = content.Control as Control;

                xtraTabControl1.TabPages.Add(xTabPageExt);
                xtraTabControl1.SelectedTabPage = xTabPageExt;
            }
        }

        IViewContent _activateViewContent;
        /// <summary>获取当前显示的 IViewContent 对象</summary>
        public IViewContent ActivateViewContent
        {
            get
            {
                WorkbenchSingleton.AssertMainThread();
                return _activateViewContent;
            }
            private set
            {
                if (_activateViewContent != value)
                {
                    _activateViewContent = value;

                    if (_activateViewContent != null) { _activateViewContent.ActivateViewContentChanged2(); }
                }
            }
        }

        private void xtraTabControl1_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            if (e.Page != null) { ActivateViewContent = (e.Page as XtraTabPageExt).ViewContent; }
            else { ActivateViewContent = null; }
        }

        private void xtraTabControl1_CloseButtonClick(object sender, EventArgs e)
        {
            ((e as DevExpress.XtraTab.ViewInfo.ClosePageButtonEventArgs).Page as XtraTabPageExt).PageVisible = false;
        }
    }
}
